<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
import moment from 'moment'
require('echarts/theme/macarons')
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    dataList: {}
  },
  watch: {
    dataList(val) {
      this.list = val
      this.initChart()
    }
  },
  data() {
    return {
      list: [],
      chart: null
    };
  },
  mounted() {
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      const timeArray = []
      const dataArray = []
      const now = moment().format('YYYY/MM/DD HH').substr(5, 9) + ':00'
      for (var index in this.list) {
        const canTime = this.list[index].time.substr(5, 11).replace('-', '/')
        timeArray.push(canTime)
        dataArray.push(this.list[index].ratio)
        // if (canTime === now) {
        //   break
        // }
      }
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        dataZoom: [{
          startValue: timeArray[0]
        }, {
          type: 'inside'
        }],
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          x: '3.8%',
          y: '17.3%',
          x2: '5.5%',
          y2: '17%'
        },
        xAxis: {
          name: '时间',
          data: timeArray
        },
        yAxis: {
          name: '压力指数',
          splitLine: {
            show: false
          }
        },
        visualMap: {
          orient: 'horizontal',
          top: 10,
          right: 'right',
          min: 0,
          max: 1,
          splitNumber: 5,
          color: ['#d94e5d', '#eac736', '#50a3ba'],
          textStyle: {
            fontSize: 12,
            color: '#85B8D9'
          }
        },
        series: {
          name: '压力指数',
          type: 'line',
          data: dataArray,
          markLine: {
            silent: true,
            data: [{
              yAxis: 0.2
            }, {
              yAxis: 0.4
            }, {
              yAxis: 0.6
            }, {
              yAxis: 0.8
            }]
          }
        }
      })
    }
  }
}
</script>
